
import axios from "axios";
import { showMessage } from "./status";
import router from "@/router";
import { ElMessage } from 'element-plus'
//导出基准地址,以备没有通过axios请求的地址使用
export const baseURL = '';
// export const baseURL = '/';
const instance = axios.create({
    baseURL,
    timeout: 8000, //8S超时
})

//请求拦截
instance.interceptors.request.use(
    (config) => {
    },
    (err) => {
        return Promise.reject(err);
    }
);
//响应拦截
instance.interceptors.response.use(
    (res) => {
        if(res.data.code === 302) {
            window.location.href = res.data.data;
        }
        return res.data;
    },
    (err) => {
        // 如果 401 状态码
        if (err.response && err.response.status === 401) {
           ElMessage.error(showMessage(401))

        } else {
            if (err.response && err.response.status) {
                ElMessage.error(showMessage(err.response.status))
            }

        }
        return Promise.reject(err);
    }
);
// 封装 GET POST PUT DELETE 请求并导出
export function request(url = '', params = {}, type = 'POST',headers = {}) {
    //设置 url params type 的默认值
    return new Promise((resolve, reject) => {
        let promise
        if (type.toUpperCase() === 'GET') {
            promise = instance({
                url,
                params
            })
        } else if (type.toUpperCase() === 'POST') {
            promise = instance({
                method: 'POST',
                url,
                data: params,
                headers,
                responseType: headers.responseType ? headers.responseType : ''
            })
        } else if (type.toUpperCase() === 'DELETE') {
            promise = instance({
                method: 'DELETE',
                url,
                data: params,
                headers
            })
        } else if (type.toUpperCase() === 'PUT') {
            promise = instance({
                method: 'PUT',
                url,
                data: params,
                headers
            })
        }
        //处理返回
        promise.then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)

        })
    })
}
